﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MovieRental.DataInterfaces;
using MovieRental.Entities;
using MovieRental.GeneralDataExceptions;


namespace MovieRental.BuisnessComponents.Base
{
    public abstract class BaseComponent<TEntity, TKey, IRepository> : INotifySourceUpdated
        where IRepository : IRepository<TEntity, TKey> 
        where TEntity : BaseEntity<TKey>
        where TKey : IEquatable<TKey>
    {
        protected IRepository Repository { private set; get; }

        public BaseComponent(IRepository repo)
        {
            Repository = repo;
        }

        public virtual TEntity Get(TKey id)
        {
            try
            {
                return Repository.Load(id);
            }
            catch (ItemNotFoundException)
            {
                return null;
            }      
        }

        public virtual IEnumerable<TEntity> GetAll()
        {
            return Repository.LoadAll();
        }

        public virtual void AddOrUpdate(TEntity obj)
        {
            Verify(obj);
            Repository.Save(obj);
            OnSourceUpdated();
        }

        public virtual void Delete(TEntity obj)
        {
            Repository.Delete(obj);
            OnSourceUpdated();
        }

        public abstract void Verify(TEntity obj);

        public event EventHandler SourceUpdated;

        protected void OnSourceUpdated()
        {
            if (SourceUpdated != null)
                SourceUpdated(this, null);
        }
        
    }
}
